import React, {Component} from 'react'
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import {hashHistory} from 'react-router'
import {actions} from '../actions'
import Station from '../components/Station'
import CartItem from '../components/CartItem'
import Checkout from '../components/Checkout'
import CarEmpty from '../components/CarEmpty'
import DeleteItem from '../components/DeleteItem'
import AddressSelect from '../components/AddressSelect'
import Gift from '../components/Gift'
import Activity from '../components/Activity'
import Guide from '../components/Guide'
import {createCheckoutParams} from '../../checkout/actions/'

@connect(
  state => ({cart: state.cart}),
  dispatch => ({
    ...bindActionCreators({
      getCartItem: actions.getCartItem,
      fetchCartItem: actions.fetchCartItem,
      fetchDelCartItem: actions.fetchDelCartItem,
      fetchSelectCartItem: actions.fetchSelectCartItem,
      changeCount: actions.changeCount,
      fetchSwitchCartItem: actions.fetchSwitchCartItem,
      fetchChangeAddress: actions.fetchChangeAddress,
      fetchChangeAct: actions.fetchChangeAct
    }, dispatch)
  })
)

export default class App extends Component {
  constructor() {
    super()

    this.state = {
      isAddressSelect: false,
      ifDel: false,
      cartId: null,
      isGuide: false,
      gift: [],
      activity: [],
      isGift: false,
      isActivity: false
    }
  }

  componentWillMount() {
    this.props.fetchCartItem().then(() => {
      this.setState({isGuide: !this.props.cart.data.isRemindGuide})
    })
  }

  // 判断全选状态
  _ifAllPick = () => {
    let data = this.props.cart.data.wchatGoodsCartActivityVos,
      status = true

    data.map(item => {
      item.wCartGoodsVos.map(i => {
        if (i.choose === false) {
          status = false
        }
      })
    })

    return status
  }

  // 全选与全不选
  _selectAll = status => {
    let cartId = ''

    this.props.cart.data.wchatGoodsCartActivityVos.map(item => {
      item.wCartGoodsVos.map(i => {
        cartId += `${i.id},`
      })
    })

    this.props.fetchSelectCartItem({
      cartId,
      cartStatus: status ? '1' : '2'
    })
  }

  // 删除商品
  _delItem = id => {
    this.setState({
      ifDel: true,
      cartId: id
    })
  }

  _cancelDel = () => {
    this.setState({
      ifDel: false,
      cartId: null
    })
  }

  _confirmDel = () => {
    this.props.fetchDelCartItem({cartId: this.state.cartId})

    this._cancelDel()
  }

  // 修改数量
  _changeCount = params => {
    let {changeCount} = this.props

    if (params.count === 0) {
      return
    } else if (params.count > 999) {
      return
    }

    params.count += ''
    params.noMessage = true

    changeCount(params)
  }

  // 自由输入修改数量
  _changeCountFree = (goodsId, e) => {
    let {changeCount} = this.props

    if (!e.target.value) {
      let cart = this.props.cart.data

      cart.wchatGoodsCartActivityVos.map(item => {
        item.wCartGoodsVos.map(i => {
          if (i.goodsId === goodsId) {
            i.count = ''
          }
        })
      })

      this.props.getCartItem(cart)
    } else {
      changeCount({count: parseInt(e.target.value), goodsId, noMessage: true})
    }
  }

  // 检测数量是否合法
  _testCount = (goodsId, e) => {
    let {changeCount, showMessage} = this.props

    if (!e.target.value) {
      showMessage('购买数量必须大于0')
      changeCount({count: 1, goodsId, noMessage: true})
    }
  }

  // 确认下单
  _confirmOrder = () => {
    createCheckoutParams({
      immediately: '2',
      goodsId: null,
      count: null
    })
    hashHistory.push('/checkout')
  }

  // 弹出地址选择
  _showAddressSelect = () => {
    this.setState({isAddressSelect: true})
  }

    // 隐藏地址选择
  _hideAddressSelect = () => {
    this.setState({isAddressSelect: false})
  }

  // 改变配送地址和方式
  _changeAddress = params => {
    this.props.fetchChangeAddress(params)
    this._hideAddressSelect()
  }

  // 关闭配送到家引导
  _closeGuide = () => {
    this.setState({isGuide: false})
  }

  // 加入购物车重新获取购物车信息
  _fetchAddToCart = params => {
    let {fetchAddToCart, fetchCartItem} = this.props

    fetchAddToCart(params).then(() => {
      fetchCartItem()
    })
  }

  // 弹出赠品选择
  _showGift = params => {
    this.setState({gift: params, isGift: true})
  }

  // 隐藏赠品选择
  _hideGift = () => {
    this.setState({isGift: false})
  }

    // 活动切换赠品
  _chooseGifts = params => {
    this.props.fetchChangeAct(params)
    this.setState({isGift: false})
  }

  // 弹出活动选择
  _showActivity = params => {
    this.setState({activity: params, isActivity: true})
  }

  // 隐藏活动选择
  _hideActivity = () => {
    this.setState({isActivity: false})
  }

  // 商品切换活动
  _chooseActivity = params => {
    this.props.fetchChangeAct(params)
    this.setState({isActivity: false})
  }

  render() {
    let {cart: {data}, fetchSelectCartItem, fetchSwitchCartItem} = this.props

    if (!data) {
      return (
        <section>
        </section>
      )
    } else {
      return (
          <section style={{height: '100%'}}>
            <section className="wrapper J-scroll" style={{paddingBottom: '1rem'}}>
              <Station
                  siteName={data.siteName}
                  siteAddress={data.siteAddress}
                  fetchSwitchCartItem={fetchSwitchCartItem}
                  canPayByCredit={data.canPayByCredit}
                  whetherIsCustomizedSite={data.whetherIsCustomizedSite}
                  type={data.type}
                  isSupportDelivery={data.isSupportDelivery}
                  showSelect={this._showAddressSelect}
                  confirmOrderAddressVos={data.confirmOrderAddressVos}
              />
                {
                    data.wchatGoodsCartActivityVos.length ? <CartItem
                        items={data.wchatGoodsCartActivityVos}
                        delCartItem={this._delItem}
                        fetchSelectCartItem={fetchSelectCartItem}
                        changeCount={this._changeCount}
                        changeCountFree={this._changeCountFree}
                        testCount={this._testCount}
                        showMessage={this.props.showMessage}
                        type={data.type}
                        showGift={this._showGift}
                        showActivity={this._showActivity}
                        showSpecification={this._showSpecification}
                        /> :
                    <CarEmpty/>
                }
              {this.state.ifDel &&
                  <DeleteItem
                      cancelDel={this._cancelDel}
                      confirmDel={this._confirmDel}
                  />
              }
            </section>
              {
                  this.state.isAddressSelect &&
                  <AddressSelect
                      cancelSelect={this._hideAddressSelect}
                      confirmOrderAddressVos={data.confirmOrderAddressVos}
                      changeAddress={this._changeAddress}
                  />
              }
              {
                  this.state.isGift &&
                  <Gift
                      items={this.state.gift}
                      chooseGifts={this._chooseGifts}
                      hideGift={this._hideGift}
                  />
              }
              {
                  this.state.isActivity &&
                  <Activity
                      items={this.state.activity}
                      chooseActivity={this._chooseActivity}
                      hideActivity={this._hideActivity}
                  />
              }
              {this.state.isGuide &&
              <Guide
                handle={this._closeGuide}
              />
              }
              <Checkout
                  totalCount={data.selectCount}
                  totalPrice={data.goodsAllPrice}
                  selectAll={this._selectAll}
                  ifAllPick={this._ifAllPick}
                  confirmOrder={this._confirmOrder}
              />
          </section>
      )
    }
  }
}
